﻿using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using System.Text;
using System.Xml;
using OBoobsWallpaper.Entity;

namespace OBoobsWallpaper.Logic
{
    public class RssGenerator
    {
        public string Generate(List<RssItem> rssItems, DateTime lastUpdateTime)
        {
            var feed = new SyndicationFeed
            {
                Title = new TextSyndicationContent("OBoobs windows wallpapers"),
                Copyright = new TextSyndicationContent("I © 2010"),
                Description = new TextSyndicationContent("The most exiting wallpapers for real guy"),
                Generator = "RSS Feed Generator",
                Id = "www.oboobs.ru",
                LastUpdatedTime = lastUpdateTime,
            };
            var link = new SyndicationLink
            {
                Title = "OBoobs.ru",
                Uri = new Uri("http://oboobs.ru")
            };
            feed.Links.Add(link);

            var feedItems = new List<SyndicationItem>();
            foreach (var item in rssItems)
            {
                var feedItem = new SyndicationItem
                {
                    Id = item.Id,
                    Title = new TextSyndicationContent(item.Title),
                };
                feedItem.Links.Add(SyndicationLink.CreateSelfLink(new Uri(item.ImageLink)));
                feedItem.Links.Add(SyndicationLink.CreateMediaEnclosureLink(new Uri(item.ImageLink), "image/JPG", 0));
                feedItems.Add(feedItem);
            }
            feed.Items = feedItems;

            var stringBuilder = new StringBuilder(1024 + 600*feedItems.Count);
            var rssWriter = XmlWriter.Create(stringBuilder);
            if (rssWriter == null)
                throw new NullReferenceException("Can not create XmlWriter from StringBuilder");
            var rssFormatter = new Rss20FeedFormatter(feed);
            rssFormatter.WriteTo(rssWriter);
            rssWriter.Close();

            return stringBuilder.ToString();
        }
    }
}